import Foundation
import Combine
import SwiftUI

// 成就结构体
struct Achievement {
    var title: String
    var description: String
    var progress: Double // 0.0 - 1.0
}

class ProfileViewModel: ObservableObject {
    @Published var userProfile = UserProfile()
    @Published var isHealthKitEnabled: Bool = false
    @Published var height: Double = 170.0 // 默认身高：170cm
    @Published var age: Int = 30 // 默认年龄：30岁
    @Published var gender: String = "male" // 默认性别：男
    
    // 成就相关属性
    @Published var streakDays: Int = 0
    @Published var achievementPoints: Int = 0
    @Published var unlockedAchievements: [String] = []
    @Published var averageDailyIntake: Double = 0.0
    @Published var goalAchievementRate: Double = 0.0
    
    // 定义成就列表
    var achievements: [Achievement] {
        [
            Achievement(title: "初学者", description: "首次记录饮水量", progress: 1.0),
            Achievement(title: "坚持不懈", description: "连续7天达到饮水目标", 
                        progress: min(Double(streakDays) / 7.0, 1.0)),
            Achievement(title: "水润达人", description: "连续30天达到饮水目标", 
                        progress: min(Double(streakDays) / 30.0, 1.0)),
            Achievement(title: "精准把控", description: "3天内饮水量与目标值相差不超过100ml", 
                        progress: calculatePrecisionProgress()),
            Achievement(title: "清晨活力", description: "连续5天在早晨8点前记录第一杯水", 
                        progress: calculateMorningProgress()),
            Achievement(title: "健康常伴", description: "使用应用满30天", 
                        progress: calculateUsageDaysProgress())
        ]
    }
    
    var totalAchievements: Int {
        return achievements.count
    }
    
    // 模拟的水摄入时间分布
    private var intakeDistribution: [Double] = [
        0.1, 0.0, 0.0, 0.0, 0.3, 0.5, // 0-6点
        1.2, 2.5, 2.8, 2.0, 1.5, 1.8, // 6-12点
        2.5, 2.2, 1.8, 1.5, 2.0, 2.5, // 12-18点
        1.8, 1.2, 0.8, 0.5, 0.3, 0.2  // 18-24点
    ]
    
    private var cancellables = Set<AnyCancellable>()
    
    init() {
        // 从UserDefaults加载用户信息
        loadUserProfile()
        
        // 初始化成就和统计数据
        isHealthKitEnabled = UserDefaults.standard.bool(forKey: "isHealthKitEnabled")
        height = UserDefaults.standard.double(forKey: "userHeight")
        if height == 0 { height = 170.0 }
        
        age = UserDefaults.standard.integer(forKey: "userAge")
        if age == 0 { age = 30 }
        
        gender = UserDefaults.standard.string(forKey: "userGender") ?? "male"
        
        // 获取饮水记录统计数据（这里使用模拟数据）
        calculateStatistics()
        
        // 加载成就
        loadAchievements()
    }
    
    // 保存用户信息
    func saveUserProfile(name: String, weight: Double) {
        userProfile.updateProfile(name: name, weight: weight)
        
        // 保存到UserDefaults
        let defaults = UserDefaults.standard
        defaults.set(name, forKey: "userName")
        defaults.set(weight, forKey: "userWeight")
        defaults.set(userProfile.goal, forKey: "userGoal")
        
        // 保存额外信息
        defaults.set(height, forKey: "userHeight")
        defaults.set(age, forKey: "userAge")
        defaults.set(gender, forKey: "userGender")
    }
    
    // 加载用户信息
    private func loadUserProfile() {
        let defaults = UserDefaults.standard
        userProfile.name = defaults.string(forKey: "userName") ?? ""
        userProfile.weight = defaults.double(forKey: "userWeight")
        
        // 如果有保存的目标，使用它，否则通过体重计算
        if let savedGoal = defaults.object(forKey: "userGoal") as? Double {
            userProfile.goal = savedGoal
        } else if userProfile.weight > 0 {
            userProfile.goal = userProfile.calculateRecommendedGoal()
        }
    }
    
    // 切换HealthKit集成状态
    func toggleHealthKitIntegration(isEnabled: Bool) {
        isHealthKitEnabled = isEnabled
        UserDefaults.standard.set(isEnabled, forKey: "isHealthKitEnabled")
        
        // 在这里可以添加实际的HealthKit集成代码
        if isEnabled {
            // 请求HealthKit权限并进行设置
            setupHealthKit()
        }
    }
    
    // 计算推荐饮水量，考虑了性别和年龄因素
    func calculateRecommendedGoal() -> Double {
        // 基础饮水量：体重 * 30ml
        var baseAmount = userProfile.weight * 30
        
        // 根据性别调整
        if gender == "male" {
            baseAmount *= 1.05 // 男性略高5%
        } else if gender == "female" {
            baseAmount *= 0.95 // 女性略低5%
        }
        
        // 根据年龄调整
        if age < 18 {
            baseAmount *= 1.1 // 青少年需要更多水分
        } else if age > 60 {
            baseAmount *= 0.95 // 老年人稍微减少
        }
        
        // 四舍五入到最接近的50ml
        return round(baseAmount / 50.0) * 50.0
    }
    
    // 计算BMI指数
    func calculateBMI() -> Double {
        guard height > 0 else { return 0 }
        // BMI = 体重(kg) / 身高²(m²)
        let heightInMeters = height / 100.0
        return userProfile.weight / (heightInMeters * heightInMeters)
    }
    
    // 获取BMI状态文本
    func getBMIStatus() -> String {
        let bmi = calculateBMI()
        switch bmi {
        case ..<18.5:
            return "偏瘦"
        case 18.5..<24:
            return "正常"
        case 24..<28:
            return "超重"
        case 28...:
            return "肥胖"
        default:
            return ""
        }
    }
    
    // 获取BMI状态颜色
    func getBMIStatusColor() -> Color {
        let bmi = calculateBMI()
        switch bmi {
        case ..<18.5:
            return .orange
        case 18.5..<24:
            return .green
        case 24..<28:
            return .orange
        case 28...:
            return .red
        default:
            return .gray
        }
    }
    
    // 配置HealthKit（占位方法，实际实现需要导入HealthKit框架）
    private func setupHealthKit() {
        // 这里将来会实现HealthKit集成
        print("HealthKit integration would be set up here")
    }
    
    // 重置用户数据
    func resetUserData() {
        userProfile = UserProfile()
        
        // 清除UserDefaults中的用户数据
        let defaults = UserDefaults.standard
        defaults.removeObject(forKey: "userName")
        defaults.removeObject(forKey: "userWeight")
        defaults.removeObject(forKey: "userGoal")
        defaults.removeObject(forKey: "userHeight")
        defaults.removeObject(forKey: "userAge")
        defaults.removeObject(forKey: "userGender")
        
        // 重置统计数据
        streakDays = 0
        achievementPoints = 0
        unlockedAchievements = []
        
        // 保存重置后的成就数据
        saveAchievements()
    }
    
    // 计算用户等级（基于成就点数）
    func calculateUserLevel() -> Int {
        // 简单的等级计算：每100点提升一级，最低1级
        let level = 1 + (achievementPoints / 100)
        return max(1, level)
    }
    
    // 获取健康建议
    func getHealthSuggestions() -> [String] {
        var suggestions: [String] = []
        
        // 根据BMI给出建议
        let bmi = calculateBMI()
        if bmi < 18.5 {
            suggestions.append("您的BMI偏低，建议适当增加热量摄入和肌肉锻炼")
        } else if bmi >= 24 {
            suggestions.append("您的BMI偏高，建议控制饮食并增加有氧运动")
        }
        
        // 根据饮水习惯给出建议
        if averageDailyIntake < userProfile.goal * 0.8 {
            suggestions.append("您的平均饮水量不足，建议设置更多提醒以增加饮水量")
        }
        
        if goalAchievementRate < 0.5 {
            suggestions.append("您的目标达成率较低，可以尝试设置更合理的目标")
        }
        
        // 根据饮水时间分布给出建议
        let morningIntake = intakeDistribution[6...11].reduce(0, +)
        let eveningIntake = intakeDistribution[18...23].reduce(0, +)
        
        if morningIntake < eveningIntake {
            suggestions.append("建议增加早晨的饮水量，有助于提高新陈代谢")
        }
        
        if intakeDistribution[22...23].reduce(0, +) > intakeDistribution.max()! * 0.3 {
            suggestions.append("睡前两小时内应减少饮水量，以免影响睡眠质量")
        }
        
        // 添加一些通用建议
        suggestions.append("饮水应当均匀分布，而不是一次性大量饮水")
        suggestions.append("适当增加运动量，可以促进新陈代谢和健康")
        
        return suggestions
    }
    
    // 获取饮水时间分布数据
    func getIntakeDistribution() -> [Double] {
        return intakeDistribution
    }
    
    // 计算统计数据（在实际应用中，这应该基于真实数据计算）
    private func calculateStatistics() {
        // 模拟数据
        averageDailyIntake = 1800
        goalAchievementRate = 0.75
        streakDays = 5
        achievementPoints = 120
    }
    
    // 以下方法用于模拟计算成就进度
    private func calculatePrecisionProgress() -> Double {
        return 0.7 // 模拟数据
    }
    
    private func calculateMorningProgress() -> Double {
        return 0.4 // 模拟数据
    }
    
    private func calculateUsageDaysProgress() -> Double {
        return 0.25 // 模拟数据
    }
    
    // 加载成就数据
    private func loadAchievements() {
        // 模拟一些已解锁的成就
        unlockedAchievements = ["初学者"]
        
        if let savedAchievements = UserDefaults.standard.stringArray(forKey: "unlockedAchievements") {
            unlockedAchievements = savedAchievements
        }
    }
    
    // 保存成就数据
    private func saveAchievements() {
        UserDefaults.standard.set(unlockedAchievements, forKey: "unlockedAchievements")
    }
} 